package cn.usian.controller;

import cn.usian.common.R;
import cn.usian.pojo.Employee;
import cn.usian.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //登录
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){//放在形参
       R<Employee> r=employeeService.login(employee);
        if (r.getCode()==1){//说明登录成功
            //将用户的信息放在session中
            session.setAttribute("employee",r.getData().getId());
        }
        return employeeService.login(employee);
    }

    //注销
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();//清除session
        return R.success("退出成功");
    }

    //分页模糊查询
    @GetMapping("/page")
    public R findPage(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int pageSize,String name){
        return employeeService.findPage(page,pageSize,name);
    }

    //添加
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        Long id =(Long) session.getAttribute("employee");
        //将创建者得id保存在employee对象中
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
         employeeService.save(employee);
        return R.success("添加成功");
    }
    //修改
    @PutMapping
    public  R updateEmp(@RequestBody Employee employee){
        employeeService.updateEmp(employee);
        return R.success("修改成功");
    }
}
